package com.linkage.educloud.ah.vnet;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import com.linkage.educloud.ah.Constants;
import com.linkage.educloud.ah.MyApplication;
import com.linkage.educloud.ah.bean.AccountData;
import com.linkage.educloud.ah.bean.ClazzContact;
import com.linkage.educloud.ah.bean.ClazzGroup;
import com.linkage.educloud.ah.config.AccountConfig;
import com.linkage.educloud.ah.data.Ws;
import com.linkage.educloud.ah.view.activity.login.LoginActivity;
import com.royasoft.im.api.Message;
import com.zzhou.common.library.util.StringUtil;

import static com.royasoft.im.api.Message.ChatType.FILE;
import static com.royasoft.im.api.Message.ChatType.IMAGE;
import static com.royasoft.im.api.Message.ChatType.TEXT;

/**
 * Created by fish902 on 2017/5/26.
 */

public class PushReceiver extends BroadcastReceiver {
    private static final String TAG = "PushReceiver";
    private Context mContext;
    private AccountData mAccountData;
    ContentResolver mResolver;


    @Override
    public void onReceive(Context context, Intent intent) {
        if (mContext == null) {
            mContext = context;
        }
        if (mResolver == null) {
            mResolver = mContext.getContentResolver();
        }
        Log.i(TAG, "FirstReceiver: ");
        String msg = intent.getStringExtra("msg");
        Log.i(TAG, "FirstReceiver msg: " + msg);
        if ("login success".equals(msg)) {
            Log.i(TAG, "PushReceive im login success get offline message");
            MyApplication.getInstance().setHasLoginIm(true);
            LinkagePushUtils.getOfflineMessages();
            if (MyApplication.getInstance().mIMessage != null && MyApplication.getInstance().mIMessage.size() > 0) {
                Log.i(TAG, "has some on wait send msg, start send");
                sendTargetMessage();
            } else {
                Log.i(TAG, "no has some on wait send msg");
            }
        } else if ("disconnected".equals(msg)) {
            Log.i(TAG, "PushReceive im disconnected");
            MyApplication.getInstance().setHasLoginIm(false);
        }
        Message message = intent.getParcelableExtra("data");
        if (message != null) {
            Log.i(TAG, "FirstReceiver text: " + message.getText());
            Log.i(TAG, "FirstReceiver ext: " + message.getExt());
            Log.i(TAG, "FirstReceiver messageType: " + message.getMessageType());
            Log.i(TAG, "FirstReceiver chatType: " + message.getChatType());
            Log.i(TAG, "FirstReceiver time: " + message.getTimestamp());
            Log.i(TAG, "FirstReceiver from: " + message.getFrom());
            Log.i(TAG, "FirstReceiver messageid: " + message.getMessageId());
            Log.i(TAG, "FirstReceiver requestid: " + message.getRequestId());
            Log.i(TAG, "FirstReceiver to: " + message.getTo());
            try {
                Log.i(TAG, "FirstReceiver file name: " + message.getFile().getName());
                Log.i(TAG, "FirstReceiver file url: " + message.getFile().getUrl());
                Log.i(TAG, "FirstReceiver file thumb: " + message.getFile().getThumb());
                Log.i(TAG, "FirstReceiver file md5: " + message.getFile().getMd5());
            } catch (Exception e) {

            }
            if (message.getMessageType() == Message.MessageType.KICKED_OFF) {
                Toast.makeText(context, "你的账号在其他设备上登录，请重新登录！", Toast.LENGTH_SHORT).show();
                MyApplication.getInstance().logout(true);
                Intent intent1 = new Intent(context, LoginActivity.class);
                intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent1);
//                MainActivity.instance.finish();
                return;
            } else if (message.getMessageType() == Message.MessageType.REQ_OFFLINE) {
                Log.i(TAG, ">>>>>>>>>>>>>>>>>>>>>>>IM is offline start relogin");
                reLoginIm();
            }
            if (StringUtil.isNullOrEmpty(message.getText())
                    &&(message.getFile()==null
                    || StringUtil.isNullOrEmpty(message.getFile().getUrl()))) {
                Log.i(TAG, ">>>>>>>>>>>>>>>>>>>>>>>IM messge is error text and file is empty");
                return;
            }
            if (!StringUtil.isNullOrEmpty(message.getTo()) &&
                    !StringUtil.isNullOrEmpty(message.getFrom())) {
                updateHistoryMsg(message);
            }
        } else {
            Log.i(TAG, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>PushReceiver messsage = null");
        }
    }

    private void sendTargetMessage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (MyApplication.getInstance().mIMessage) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    for (final ErrorMessage msg :
                            MyApplication.getInstance().mIMessage) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (msg.getMsgType()!= PushConsts.ChatType.TEXT) {
                            Log.i(TAG, "send onWait message , message type file");
                            sendFileMessage(msg);
                        } else {
                            Log.i(TAG, "send onWait message , message type text");
                            sendTxtMessage(msg);
                        }
                    }
                }
                MyApplication.getInstance().clearTargetMessage();
            }
        }).start();
    }

    private void sendFileMessage(final ErrorMessage message) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                LinkagePushUtils.UploadFile(message.getMessage(), 3000, new UploadCallback() {
                    @Override
                    public void onComplete(String s) {
                        Log.i(TAG, "send onWait message ,upload file is success " + s);
                        message.setMessage(s);
                        sendTxtMessage(message);
                    }

                    @Override
                    public void onError(int i, String s) {
                        Log.i(TAG, "send onWait message ,upload file is fail " + s);
                        updateMessageStatus(message.getUri(), "", Ws.MessageType.MSG_STATUS_ERROR);
                    }

                    @Override
                    public void onProgress(long l, long l1) {

                    }
                });
            }
        }).start();
    }

    private void sendTxtMessage(final ErrorMessage message) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (message.getChatType() == Constants.ChatType.CHAT_TYPE_SINGLE) {
                    LinkagePushUtils.sendMessage(message.getMsgType(), message.getMessage(), message.getBuddyid(), "extendTxt", new MessageCallback() {
                        @Override
                        public void onSuccess(Object o) {
                            Log.i(TAG, "send onWait message ,send single text is success " + o.toString());
                            updateMessageStatus(message.getUri(), o.toString(), Ws.MessageType.MSG_STATUS_SENT);
                        }

                        @Override
                        public void onError(String s) {
                            Log.i(TAG, "send onWait message ,send single text is fail " + s);
                            updateMessageStatus(message.getUri(), "", Ws.MessageType.MSG_STATUS_ERROR);
                        }
                    });
                } else {
                    LinkagePushUtils.sendGroupMessage(message.getMsgType(), message.getMessage(), message.getBuddyid(), "extendTxt", new MessageCallback() {
                        @Override
                        public void onSuccess(Object o) {
                            Log.i(TAG, "send onWait message ,send group text is success " + o.toString());
                            updateMessageStatus(message.getUri(), o.toString(), Ws.MessageType.MSG_STATUS_SENT);
                        }

                        @Override
                        public void onError(String s) {
                            Log.i(TAG, "send onWait message ,send group text is fail " + s);
                            updateMessageStatus(message.getUri(), "", Ws.MessageType.MSG_STATUS_ERROR);
                        }
                    });
                }
            }
        }).start();
    }

    private void updateMessageStatus(Uri uri, String server_time, int msgstutas) {
        ContentValues cv = new ContentValues();
        cv.put(Ws.MessageTable.OUTBOUND_STATUS, msgstutas);
        if (!StringUtil.isNullOrEmpty(server_time)) {
            cv.put(Ws.MessageTable.SENT_TIME, Long.parseLong(server_time));//因为按照SENT_TIME排序
            cv.put(Ws.MessageTable.RECEIVED_TIME, Long.parseLong(server_time));
        }
        mContext.getContentResolver().update(uri, cv, null, null);
    }

    private void updateHistoryMsg(final Message msg) {
        mAccountData = AccountConfig.getLoginAccount();
        new Thread(new UpdateHistory(msg)).start();
    }

    private class UpdateHistory implements Runnable {
        private Message message;

        public UpdateHistory(Message msg) {
            this.message = msg;
        }

        @Override
        public synchronized void run() {
            // String content = "";
            ContentResolver resolver;

            if (null != mContext) {
                resolver = mContext.getContentResolver();
                if (null == resolver) {
                    Log.e(TAG, TAG + ", resolver is null");
                    return;
                }
            } else {
                return;
            }

            // Cursor cr;
            String accountName = mAccountData.getLoginAccount();
            int chatType;
            String buddyid;
            ContentValues cv;
//            ClazzWorkContact contact = null;
//            ClazzWorkContactGroup classRoom = null;

//            for (int i = 0; i < cm.getCount(); i++) {
            cv = new ContentValues();
            cv.put(Ws.MessageTable.ACCOUNT_NAME, accountName);
            // cv.put(ThreadTable.MSG_RECEIVED_TIME, (int)
            // conver.getDate());
            if (StringUtil.isNullOrEmpty(message.getFrom()) || message.getFrom().length()<= PushConsts.VID_P.length()) {
                return;
            }
            if (StringUtil.equals(message.getFrom().substring(PushConsts.VID_P.length()), "" + mAccountData.getUserId())) {//貌似不需要判断，但不影响只不过应该不会走到里面
                cv.put(Ws.MessageTable.IS_INBOUND, Ws.MessageType.OUTGOINT);
//                cv.put(Ws.MessageTable.UNREAD_COUNT, 0);
                cv.put(Ws.MessageTable.SENT_TIME, (long) message.getTimestamp());
            } else {
                cv.put(Ws.MessageTable.IS_INBOUND, Ws.MessageType.INCOMING);
//                cv.put(Ws.MessageTable.UNREAD_COUNT, 1);//这个数要算，暂时设为1
                cv.put(Ws.MessageTable.RECEIVED_TIME,
                        (long) message.getTimestamp());
                cv.put(Ws.MessageTable.SENT_TIME, message.getTimestamp());
            }
            Log.i(TAG, "messagetype = " + message.getMessageType());
            switch (message.getMessageType()) {
                case Message.MessageType.CHAT_GROUP:
                    // 来自IM的群组聊天，去掉前缀"1000"
                    Log.i(TAG, "=============Group Chat " + Message.MessageType.CHAT_GROUP);
                    buddyid = message.getTo();
                    ClazzGroup group = MyApplication.getInstance().getResovler()
                            .getContactGroupById(mAccountData.getLoginAccount(), buddyid);
//                    ClazzGroup group = mResolver.query(Ws.GroupTable.CONTENT_URI,null,
//                            Ws.GroupTable.ACCOUNT_NAME + " =? and " + Ws.GroupTable.REMOTEID + " =?",
//                            new String[]{},null);
                    if (group != null) {
                        if (Constants.GROUP_TYPE_CREATE_TEMP_GROUP == group.type) {
                            cv.put(Ws.MessageTable.THREAD_TYPE, Constants.ThreadType.THREAD_TEMP_GROUP);
                        } else {
                            cv.put(Ws.MessageTable.THREAD_TYPE, Constants.ThreadType.THREAD_IM_CLASS);
                        }
                    } else {
                        return;
                    }
                    cv.put(Ws.MessageTable.BUDDY_ID, buddyid);
                    cv.put(Ws.MessageTable.SENDER_ID, message.getFrom().substring(PushConsts.VID_P.length()));
                    cv.put(Ws.MessageTable.CHAT_TYPE, Constants.ChatType.CHAT_TYPE_GROUP);
                    break;
                default:
                case Message.MessageType.CHAT_SINGLE:
                    Log.i(TAG, "=============Single Chat ");
                    if (StringUtil.isNullOrEmpty(message.getFrom()) || message.getFrom().length()<= PushConsts.VID_P.length()) {
                        return;
                    }
                    buddyid = message.getFrom().substring(PushConsts.VID_P.length());
                    String type = message.getFrom().substring(0,PushConsts.VID_P.length());
                    int useType = 0;
                    if (PushConsts.VID_P.equals(type)) {
                        useType = 1;//通讯录返回家中类型为1 和登录类型值不同
                    }else if (PushConsts.VID_T.equals(type)) {
                        useType = 2;//教师
                    }else{
                        Log.e(TAG,"用户类型异常 usetype = " + useType);
                    }
                    ClazzContact contact = MyApplication.getInstance().getResovler()
                            .getContactById(mAccountData.getLoginAccount(), buddyid,useType);
                    if (contact == null) {
                        return;
                    }
                    cv.put(Ws.MessageTable.BUDDY_ID, message.getFrom());
                    cv.put(Ws.MessageTable.SENDER_ID, buddyid);
                    cv.put(Ws.MessageTable.THREAD_TYPE, Constants.ThreadType.THREAD_IM_SINGE);
                    cv.put(Ws.MessageTable.CHAT_TYPE, Constants.ChatType.CHAT_TYPE_SINGLE);
                    break;
            }
            Log.i(TAG, "ChatType = " + message.getChatType() + " text = " + message.getText());
            switch (message.getChatType()) {
                default:
                case TEXT:
                    cv.put(Ws.MessageTable.BODY, message.getText());
                    chatType = Ws.MessageType.TYPE_MSG_TEXT;
                    break;
                case IMAGE:
                    cv.put(Ws.MessageTable.BODY, message.getFile().getUrl());
                    chatType = Ws.MessageType.TYPE_MSG_PIC;
                    break;
                case FILE:
                    cv.put(Ws.MessageTable.BODY, message.getFile().getUrl());
                    chatType = Ws.MessageType.TYPE_MSG_AUDIO;
                    break;
//                case FILE:
//                    cv.put(Ws.MessageTable.BODY, message.getFile().getUrl());
//                    chatType = Ws.MessageType.TYPE_MSG_FILE;
//                    break;
            }
            cv.put(Ws.MessageTable.TYPE, chatType);
            Log.i(TAG, "============ready insert============");
            resolver.insert(Ws.MessageTable.CONTENT_URI, cv);
//            }
//            L.d(TAG, "im chat is font  " + VNewChatActivity.ACTIVITY_ISFONT);
//            if (VNewChatActivity.ACTIVITY_ISFONT) {
//                ContentValues values = new ContentValues();
//                values.put(Ws.ThreadTable.UNREAD_COUNT, 0);
//                resolver.update(Ws.ThreadTable.CONTENT_URI, values, Ws.ThreadTable.BUDDY_ID + " =? and "
//                        + Ws.ThreadTable.ACCOUNT_NAME + " =?", new String[]{buddyid, mAccountData.getLoginAccount()});
//            }
            mContext.sendBroadcast(new Intent(Ws.ThreadTable.CONTENT_CHAGED));
        }
    }

    private void reLoginIm() {
        mAccountData = AccountConfig.getLoginAccount();
        LinkagePushUtils.initPushUser(mContext, mAccountData.getUserId() + "", mAccountData.getUserId() + "", new ConnectPushInterface() {
            @Override
            public void SuccessConnectPush() {
                LinkagePushUtils.connectPush(mContext, PushConsts.SDK_APP_ID, PushConsts.SDK_APP_SEC, mAccountData.getUserId() + "", new ConnectPushInterface() {
                    @Override
                    public void SuccessConnectPush() {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                LinkagePushUtils.getOfflineMessages();
                            }
                        }).start();
                    }

                    @Override
                    public void FailerConnectPush(int ret, String msg) {
                        Toast.makeText(mContext, "聊天服务器登录失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void FailerConnectPush(int ret, String msg) {
                Toast.makeText(mContext, "聊天服务器初始化失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
